package com.charonmc.utils.mysql;

import javax.annotation.Nullable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Objects;


/**
 * DeleteUtils是管理删除行数据有关的对象
 * @author ChuYang
 */

public class DeleteUtils extends SqlManager{
    PreparedStatement ps;
    private ArrayList<Object> value = new ArrayList<>();
    private int sqlRowCount;

    /**
     * 创建对象
     * @param connection SQLManager传入连接
     */
    public DeleteUtils(Connection connection){
        this.connection = connection;
    }

    /**
     * 指定数据表
     * @param table 所要操作的数据表
     * @return {@link DeleteUtils}
     */
    public DeleteUtils inTable(String table){
        this.sql.append(table);
        return this;
    }

    /**
     * 创建约束条件
     * @param limitName 约束索引名
     * @param limitValue 约束索引值
     * @return {@link DeleteUtils}
     */
    public DeleteUtils addCondition(String limitName, @Nullable String operator, Object limitValue){
        value.add(limitValue);
        if (!Objects.equals(operator, "=") && !Objects.equals(operator, "<") && !Objects.equals(operator, ">") && !Objects.equals(operator, "!="))
        {
            return this;
        }
        if (sql.indexOf(" WHERE ") == -1) {
            this.sql.append(" WHERE ").append(limitName).append(operator).append("?");
        }else {
            this.sql.append(" & ").append(limitName).append(operator).append("?");
        }
        return this;
    }

    /**
     * 创建相等约束条件
     * @param limitName 约束索引名
     * @param limitValue 约束索引值
     * @return {@link DeleteUtils}
     */
    public DeleteUtils addCondition(String limitName, Object limitValue){
        value.add(limitValue);
        if (sql.indexOf(" WHERE ") == -1) {
            this.sql.append(" WHERE ").append(limitName).append("=").append("?");
        }else {
            this.sql.append(" & ").append(limitName).append("=").append("?");
        }
        return this;
    }

    /**
     * 构建sql语句
     * @return {@link DeleteUtils}
     * @throws SQLException 数据库异常
     */
    public DeleteUtils build() throws SQLException {
        this.ps = connection.prepareStatement(this.sql.toString());
        for (int i = 0; i < value.size(); i++) {
            ps.setObject(i + 1, value.get(i));
        }
        return this;
    }

    /**
     * 执行sql语句
     * @return {@link DeleteUtils}
     * @throws SQLException 数据库异常
     */
    public DeleteUtils execute() throws SQLException {
        sqlRowCount = ps.executeUpdate();
        return this;
    }

    /**
     * 获得受影响的行数
     * @return 受影响的行数
     */
    public int getResult(){
        return this.sqlRowCount;
    }
}
